package com.codebox.knowledge.richtext;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.BlurMaskFilter;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Browser;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.text.style.MaskFilterSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StrikethroughSpan;
import android.text.style.StyleSpan;
import android.text.style.SubscriptSpan;
import android.text.style.SuperscriptSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.codebox.common.base.BaseActivity;
import com.codebox.common.common.RouterPath;
import com.codebox.knowledge.R;
import com.codebox.knowledge.databinding.ActivityRichTextBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Able
 * @date 2019/5/15
 */

@Route(path = RouterPath.KnowledgeRouterPath.PATH_RICH_TEXT)
public class RichTextActivity extends BaseActivity<ActivityRichTextBinding> {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rich_text);

        initView();
    }

    private void initView() {
        setTitle("SpannableString");

        setForeground(mBinding.tvForegroundColorSpan);
        setBackground(mBinding.tvBackgroundColorSpan);
        setRelativeSize(mBinding.tvRelativeSizeSpan);
        setStrikethrough(mBinding.tvStrikethroughSpan);
        setUnderline(mBinding.tvUnderlineSpan);
        setSuperscriptSpan(mBinding.tvSuperscriptSpan);
        setSubscriptSpan(mBinding.tvSubscriptSpan);
        setStyleSpan(mBinding.tvStyleSpan);
        setImageSpan(mBinding.tvImageSpan);
        setClickableSpan(mBinding.tvClickableSpan);
        setUrlSpan(mBinding.tvURLSpan);
        setBlurMaskFilter(mBinding.tvBlurMaskFilter);
        setEmbossMaskFilter(mBinding.tvEmbossMaskFilter);

        setTest(mBinding.tvTest);
    }

    private void setEmbossMaskFilter(TextView tv) {
        SpannableString spannableString = new SpannableString("为文字设置浮雕");
        MaskFilterSpan maskFilterSpan = new MaskFilterSpan(
                new EmbossMaskFilter(new float[]{10, 10, 10}, 0.5f, 1f, 1f));
        spannableString.setSpan(maskFilterSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setBlurMaskFilter(TextView tv) {
        SpannableString spannableString = new SpannableString("为文字设置模糊");
        MaskFilterSpan maskFilterSpan = new MaskFilterSpan(new BlurMaskFilter(10, BlurMaskFilter.Blur.INNER));
        spannableString.setSpan(maskFilterSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setUrlSpan(TextView tv) {
        SpannableString spannableString = new SpannableString("为文字设置超链接");
        URLSpan urlSpan = new URLSpan("http://www.baidu.com/");
        spannableString.setSpan(urlSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setHighlightColor(Color.parseColor("#ff0000"));
        tv.setText(spannableString);
    }

    private void setClickableSpan(TextView tv) {
        SpannableString spannableString = new SpannableString("为文字设置点击事件");
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "你点击了我", Snackbar.LENGTH_SHORT).show();
                Uri uri = Uri.parse("http://www.baidu.com");
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Log.e("--ClickableSpan--", "Actvity was not found for intent, " + intent.toString());
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#abc123"));
                ds.setUnderlineText(true);
            }
        }, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
        tv.setHighlightColor(Color.parseColor("#abc123"));
        tv.setText(spannableString);
    }

    private void setImageSpan(TextView tv) {
        SpannableString spannableString = new SpannableString("在文本中添加xx");
        Drawable drawable = getResources().getDrawable(R.mipmap.ic_launcher);
        int drawHeight = drawable.getMinimumHeight();
        drawable.setBounds(0, 0, drawHeight, drawHeight);
        ImageSpan imageSpan = new ImageSpan(drawable);
        spannableString.setSpan(imageSpan, 6, 8, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setStyleSpan(TextView tv) {
        SpannableString spannableString = new SpannableString("为文字设置粗体,斜体风格");
        StyleSpan styleSpan_B = new StyleSpan(Typeface.BOLD);
        StyleSpan styleSpan_I = new StyleSpan(Typeface.ITALIC);
        spannableString.setSpan(styleSpan_B, 5, 7, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(styleSpan_I, 8, 10, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setSubscriptSpan(TextView tv) {
        SpannableString spannableString = new SpannableString("注释1");
        SubscriptSpan subscriptSpan = new SubscriptSpan();
        spannableString.setSpan(subscriptSpan, 2, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setSuperscriptSpan(TextView tv) {
        SpannableString spannableString = new SpannableString("你有新消息了" + "●");
        SuperscriptSpan superscriptSpan = new SuperscriptSpan();
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#FF0000"));
        spannableString.setSpan(colorSpan, 6, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spannableString.setSpan(superscriptSpan, 6, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setUnderline(TextView tv) {
        SpannableString spannableString = new SpannableString("我是文本下划线");
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannableString.setSpan(underlineSpan, 4, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);

        // 方法二
        // tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
    }

    private void setStrikethrough(TextView tv) {
        SpannableString spannableString = new SpannableString("我是文本中划线");
        StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
        spannableString.setSpan(strikethroughSpan, 3, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);

        // 方法二
        // tv.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 设置中划线并加清晰
    }

    private void setRelativeSize(TextView tv) {
        SpannableString spannableString = new SpannableString("9月22日");
        RelativeSizeSpan sizeSpan = new RelativeSizeSpan(2.0f);
        spannableString.setSpan(sizeSpan, 0, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setBackground(TextView tv) {
        SpannableString spannableString = new SpannableString("设置文字的背景色");
        BackgroundColorSpan colorSpan = new BackgroundColorSpan(Color.parseColor("#AC00FF30"));
        spannableString.setSpan(colorSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    private void setForeground(TextView tv) {
        SpannableString spannableString = new SpannableString("设置文字的前景色");
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#0099EE"));
        spannableString.setSpan(colorSpan, 5, spannableString.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        tv.setText(spannableString);
    }


    private void setTest(TextView tv) {
        tv.setText("Everything will be ok in the end, if it's not ok, it's not the end. ", TextView.BufferType.SPANNABLE);
        getEachParagraph(tv);
        tv.setMovementMethod(LinkMovementMethod.getInstance());
    }

    public void getEachParagraph(TextView textView) {
        Spannable spans = (Spannable) textView.getText();
        Integer[] indices = getIndices(textView.getText().toString().trim(), ',');
        int start = 0;
        int end = 0;
        // recycle
        for (int i = 0; i <= indices.length; i++) {
            ClickableSpan clickSpan = getClickableSpan();
            //setspan
            end = (i < indices.length ? indices[i] : spans.length());
            spans.setSpan(clickSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            start = end + 1;
        }
        //改变选中文本的高亮颜色
        textView.setHighlightColor(Color.BLUE);
    }

    private ClickableSpan getClickableSpan() {
        return new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                TextView tv = (TextView) widget;
                String s = tv.getText().subSequence(tv.getSelectionStart(), tv.getSelectionEnd()).toString();
                Log.e("onclick--:", s);
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.BLACK);
                ds.setUnderlineText(false);
            }
        };
    }

    public static Integer[] getIndices(String s, char c) {
        int pos = s.indexOf(c, 0);
        List<Integer> indices = new ArrayList<Integer>();
        while (pos != -1) {
            indices.add(pos);
            pos = s.indexOf(c, pos + 1);
        }
        return (Integer[]) indices.toArray(new Integer[0]);
    }
}
